package com.qiangesoft.bootcodegen.utils;

import com.qiangesoft.bootcodegen.entity.BcgDataSource;
import com.qiangesoft.bootcodegen.pojo.bo.BcgTableBO;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * DB工具类
 *
 * @author qiangesoft
 * @date 2024-03-15
 */
@Slf4j
public class DbUtil {

    /**
     * 获得数据库连接
     *
     * @param driverClassName
     * @param url
     * @param username
     * @param password
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public static Connection getConnection(String driverClassName, String url, String username, String password) throws ClassNotFoundException, SQLException {
        // 加载驱动
        Class.forName(driverClassName);
        // 获取连接
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }

    /**
     * 获取表信息
     *
     * @param datasource
     * @param sql
     * @return
     */
    public static List<BcgTableBO> getTableList(BcgDataSource datasource, String sql) {
        List<BcgTableBO> tableList = new ArrayList<>();
        try {
            Connection connection = getConnection(datasource.getDriverClassName(), datasource.getUrl(), datasource.getUsername(), datasource.getPassword());
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            // 查询数据
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                BcgTableBO table = new BcgTableBO();
                table.setTableName(rs.getString("table_name"));
                table.setTableComment(rs.getString("table_comment"));
                tableList.add(table);
            }
            connection.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return tableList;
    }

}